package logic

import (
	"context"
	"fmt"
	"message/model/mysql"
	"message/model/redis"

	"message/messagerpc/internal/svc"
	"message/messagerpc/messagerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *messagerpc.UserRegisterRequest) (*messagerpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("sendSmsregister" + in.Tel)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("短信验证码不正确，请重新输入")
	}
	var finduser mysql.User
	mysql.DB.Debug().Model(&mysql.User{}).Where("tel=?", in.Tel).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("当前手机号已经注册，请输入新手机号")
	}
	user := mysql.User{
		Tel: in.Tel,
	}
	mysql.DB.Debug().Create(&user)
	return &messagerpc.UserRegisterResponse{Id: int64(user.ID)}, nil
}
